//class made by Teo ( www.teodorfilimon.com ). More about the app in readme.txt

package com.teo.tools.counter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.teo.tools.counter.Counter.CounterState;
import com.teo.tools.counter.units.Unit;

/**
 * Main activity of the app
 */
public class TimeCounter extends Activity {
  // public static final boolean FREE = true;
  private static final String PREFERENCES = "ClickerCounter";
  private static final String COUNTER_VALUE = "CounterValue";
  private static final String TIME_UNIT = "TimeUnit";

  private static Counter mCounter;
  private static TextView mCountTextView;
  private static TextView mTimeTextView;
  private static TextView mGapTextView;
  private static TextView mValueTextView;
  private static ScrollView mScrollView;
  // private static Button mClipboardButton;
  // private static Button mExportButton;
  private static DB mDbHelper;
  private static Unit mUnit;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // initializing the DB
    mDbHelper = new DB(this);
    mDbHelper.open();

    // initializing UI elements
    mCountTextView = (TextView) findViewById(R.id.count);
    mTimeTextView = (TextView) findViewById(R.id.time);
    mGapTextView = (TextView) findViewById(R.id.gap);
    mValueTextView = (TextView) findViewById(R.id.value);
    mScrollView = (ScrollView) findViewById(R.id.scrollView);
    // mClipboardButton = (Button) findViewById(R.id.clipboardButton);
    // mExportButton = (Button) findViewById(R.id.exportButton);

    // setting handlers for the increment button
    Button button = (Button) findViewById(R.id.incrementButton);
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        counterEvent(mCounter.increment());
      }
    });

    // setting handlers for the decrement button
    button = (Button) findViewById(R.id.decrementButton);
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        counterEvent(mCounter.decrement());
      }
    });

    // setting handlers for the help button
    button = (Button) findViewById(R.id.helpButton);
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        Intent myIntent = new Intent(Intent.ACTION_VIEW);
        myIntent.setData(Uri.parse(arg0.getContext().getString(
            R.string.url_help)));
        startActivity(myIntent);
      }
    });

    // getting last value of the counter and the last selected unit
    final SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
    long lastValue = settings.getLong(COUNTER_VALUE, 0);
    mCountTextView.setText(Long.toString(lastValue));
    mCounter = new Counter(lastValue);
    // setting up time unit spinner
    Spinner s = (Spinner) findViewById(R.id.unitSpinner);
    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this,
        R.array.units, android.R.layout.simple_spinner_item);
    adapter
        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s.setAdapter(adapter);
    int lastUnit = settings.getInt(TIME_UNIT, 0);
    s.setSelection(lastUnit);
    setTimeUnit(lastUnit);
    s.setOnItemSelectedListener(new OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
          long arg3) {
        setTimeUnit(arg2);
        Editor e = settings.edit();
        e.putInt(TIME_UNIT, arg2);
        e.commit();
      }

      @Override
      public void onNothingSelected(AdapterView<?> arg0) {
      }
    });
    resetStats();

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
      LinearLayout ll = (LinearLayout) findViewById(R.id.resetLayout);
      ll.setVisibility(View.GONE);
      ll = (LinearLayout) findViewById(R.id.featureLayout);
      ll.setVisibility(View.GONE);
      return;
    }

    // setting handlers for the count reset button
    button = (Button) findViewById(R.id.resetCount);
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        resetCount();
      }
    });

    // setting handlers for the stats reset button
    button = (Button) findViewById(R.id.resetStats);
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        TimeCounter.resetStats();
        mDbHelper.reset();
      }
    });

    // setting handlers for global reset button
    button = (Button) findViewById(R.id.resetAll);
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        resetCount();
        resetStats();
        mDbHelper.reset();
      }
    });

    // setting handlers for the clipboard copy button
    button = (Button) findViewById(R.id.clipboardButton);
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        CounterState cs = Counter.currentState;
        ((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE))
            .setText(mUnit.getStringValue(cs.totalMillis) + " " + mUnit.getStringValue(cs.millis) + " " + cs.count);
      }
    });

    // setting handlers for the CSV export button
    button = (Button) findViewById(R.id.exportButton);
    button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        Context c = arg0.getContext();
        String path;
        if ((path = mDbHelper.exportToCSV()) != null) {
          Toast.makeText(c, c.getText(R.string.export_ok) + "\n" + path,
              Toast.LENGTH_LONG).show();
        } else {
          Utils.showDialog(R.string.message, R.string.export_fail, c);
        }
      }
    });
  }

  /**
   * This is what happens when the increment or decrement button is pushed
   * 
   * @param cs
   *          The CounterState with new info to be displayed
   */
  private final void counterEvent(CounterState cs) {
    // free version notification
    /*
     * if (TimeCounter.FREE && (cs.count == 10 || cs.count == -10)) {
     * Toast.makeText(this, R.string.free_version, Toast.LENGTH_LONG) .show(); }
     */

    String value = Long.toString(cs.count);
    mCountTextView.setText(value);
    mGapTextView.append(mUnit.getStringValue(cs.millis) + '\n');
    mValueTextView.append(value + '\n');
    mTimeTextView.append(mUnit.getStringValue(cs.totalMillis) + '\n');
    mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
    mScrollView.scrollBy(0, 20);
    mDbHelper.insert(cs);
  }

  @Override
  protected void onPause() {
    super.onDestroy();
    SharedPreferences.Editor editor = getSharedPreferences(PREFERENCES, 0)
        .edit();
    editor.putLong(COUNTER_VALUE, mCounter.getValue());
    editor.commit();
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence("1", mTimeTextView.getText());
    outState.putCharSequence("2", mGapTextView.getText());
    outState.putCharSequence("3", mValueTextView.getText());
  }

  @Override
  protected void onRestoreInstanceState(Bundle state) {
    mTimeTextView.setText(state.getCharSequence("1"));
    mGapTextView.setText(state.getCharSequence("2"));
    mValueTextView.setText(state.getCharSequence("3"));
    // mClipboardButton.setEnabled(true);
    // mExportButton.setEnabled(true);
  }

  /**
   * Resets the count
   */
  private final void resetCount() {
    counterEvent(mCounter.resetCount());
  }

  /**
   * Resets the stats about the counting
   */
  private static final void resetStats() {
    String unit = " (" + mUnit.toString() + ")\n";
    mTimeTextView.setText(R.string.time);
    mTimeTextView.append(unit);
    mGapTextView.setText(R.string.gap);
    mGapTextView.append(unit);
    mValueTextView.setText(R.string.value);
    mValueTextView.append("\n");
    // mClipboardButton.setEnabled(false);
    // mExportButton.setEnabled(false);
    mCounter.resetStats();
  }

  private final void setTimeUnit(int unit) {
    switch (unit) {
    case 0:
      mUnit = new Unit(1, this.getString(R.string.millis));
      break;
    case 1:
      mUnit = new Unit(1000, this.getString(R.string.seconds));
      break;
    }
    Cursor c = mDbHelper.getCursor();
    if (c.getCount() < 1) {
      return;
    }
    int time = c.getColumnIndex(DB.KEY_TIME);
    int gap = c.getColumnIndex(DB.KEY_GAP);
    int value = c.getColumnIndex(DB.KEY_VALUE);
    TextView timeTv = mTimeTextView;
    TextView gapTv = mGapTextView;
    TextView valueTv = mValueTextView;
    String unitString = " (" + mUnit.toString() + ")\n";
    timeTv.setText(R.string.time);
    timeTv.append(unitString);
    gapTv.setText(R.string.gap);
    gapTv.append(unitString);
    valueTv.setText(R.string.value);
    valueTv.append("\n");
    c.moveToFirst();
    do {
      timeTv.append(mUnit.getStringValue(c.getLong(time)) + '\n');
      gapTv.append(mUnit.getStringValue(c.getLong(gap)) + '\n');
      valueTv.append(Long.toString(c.getLong(value)) + '\n');
    } while (c.moveToNext());
    c.close();
  }
}